package com.sqx.modules.errand.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.entity.WMPoint;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.agentCityDetails.entity.AgentCityDetails;
import com.sqx.modules.agentCityDetails.service.AgentCityDetailsService;
import com.sqx.modules.agentUserMoney.entity.AgentUserMoney;
import com.sqx.modules.agentUserMoney.service.AgentUserMoneyService;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.banArea.entity.BanArea;
import com.sqx.modules.banArea.service.IBanAreaService;
import com.sqx.modules.cityInfo.entity.CityInfo;
import com.sqx.modules.cityInfo.service.CityInfoService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.creditRecord.service.CreditRecordService;
import com.sqx.modules.errand.dao.IndentDao;
import com.sqx.modules.errand.entity.*;
import com.sqx.modules.errand.service.EvaluateService;
import com.sqx.modules.errand.service.IndentService;

import com.sqx.modules.errand.vo.*;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.packageTime.entity.PackageTime;
import com.sqx.modules.packageTime.service.PackageTimeService;
import com.sqx.modules.reward.entity.Reward;
import com.sqx.modules.reward.service.RewardService;
import com.sqx.modules.sysUserAddress.entity.SysUserAddress;
import com.sqx.modules.sysUserAddress.service.ISysUserAddressService;
import com.sqx.modules.tbCoupon.entity.TbCouponUser;
import com.sqx.modules.tbCoupon.service.TbCouponUserService;
import com.sqx.modules.timedtask.entity.RiderLocation;
import com.sqx.modules.timedtask.service.RiderLocationService;
import com.sqx.modules.utils.HttpClientUtil;
import com.sqx.modules.utils.SenInfoCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import static org.bouncycastle.asn1.x500.style.RFC4519Style.c;


@Service
@Slf4j
public class IndentServiceImpl extends ServiceImpl<IndentDao, Indent> implements IndentService {

    @Autowired
    private IndentDao indentDao;
    @Autowired
    private TbCouponUserService couponUserService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private RewardService rewardService;
    @Autowired
    private RiderLocationService locationService;
    @Autowired
    private EvaluateService evaluateService;
    @Autowired
    private IBanAreaService banAreaService;
    @Autowired
    private CreditRecordService recordService;
    @Autowired
    private CityInfoService cityInfoService;
    @Autowired
    private ISysUserAddressService userAddressService;
    @Autowired
    private AgentCityDetailsService agentCityDetailsService;
    @Autowired
    private AgentUserMoneyService agentUserMoneyService;
    @Autowired
    private PackageTimeService packageTimeService;


    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);

    @Override
    public Indent findIndentByIndentNumber(String indentNumber) {
        return baseMapper.selectIndentByIndentNumber(indentNumber);
    }

    @Override
    public Indent findIndentByPayOrdersNo(String ordersNo) {
        return baseMapper.selectOne(new QueryWrapper<Indent>().eq("pay_orders_no", ordersNo));
    }

    //根据双方经纬度计算距离
    @Override
    public Result distance(Double ol, Double od, Double dl, Double dd, Integer type) {
        return Result.success().put("data", getDistance(ol, od, dl, dd, type));
    }

    /**
     * @param type 1.驾车（driving）2.步行（walking） 3骑行（bicycling） 4.电动车（ebicycling） 5.公交（transit）
     * @return
     */
    public TxDirection getDistance(Double lat, Double lng, Double toLat, Double toLng, Integer type) {
        if (type == null) {
            type = 1;
        }
//        https://lbs.qq.com/service/webService/webServiceGuide/webServiceRoute
        String portation = "";
        switch (type) {
            case 1:
                portation = "driving";
                break;
            case 2:
                portation = "walking";
                break;
            case 3:
                portation = "bicycling";
                break;
            case 4:
                portation = "ebicycling";
                break;
            case 5:
                portation = "transit";
                break;
            case 6:
                return null;
        }

        TxDirection txDirection = new TxDirection();
        CommonInfo one = commonInfoService.findOne(128);
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/";
        Map<String, String> maps = new HashMap<>();
        maps.put("from", lat + "," + lng);
        maps.put("to", toLat + "," + toLng);
        maps.put("key", one.getValue());
        /**
         * get_mp:是否返回多方案，取值：
         * 0 [默认]仅返回一条路线方案
         * 1 返回多方案（最多可返回三条方案供用户备选）
         */
        maps.put("get_mp", "0");
        String data = HttpClientUtil.doGet(url, maps);
        JSONObject jsonObject = JSON.parseObject(data);
        String status = jsonObject.getString("status");
        if ("0".equals(status)) {
            JSONObject result = jsonObject.getJSONObject("result");
            JSONArray routes = result.getJSONArray("routes");
            txDirection.setDistance(new BigDecimal(routes.getJSONObject(0).getString("distance")));
            txDirection.setDuration(new BigDecimal(routes.getJSONObject(0).getString("duration")));
            JSONArray polylineJson = routes.getJSONObject(0).getJSONArray("polyline");

            txDirection.setPolyline(polylineJson.toString());
        } else {
            log.error("路线计算失败:" + jsonObject.getString("message"));
        }
        return txDirection;
    }

    //查询超过五分钟未支付的订单
    @Override
    public List<Indent> findNoPay() {
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, -5);// 5分钟之前的时间
        Date beforeD = beforeTime.getTime();
        String before5 = new SimpleDateFormat("yyyyMMddHHmmss").format(beforeD);  // 前五分钟时间
        return indentDao.findNoPay(before5);
    }

    @Override
    public int cancelIndent(String indentNumber) {
        return indentDao.cancelIndent(indentNumber);
    }


    @Override
    public Result basicsMoney(Long userId, BasicsVo basicsVo) {
        String value = commonInfoService.findOne(371).getValue();
        //是否开启检测限制区域下单和城市是否开通
        if ("是".equals(value)) {
            if (!cityInfoService.isOpenCity(basicsVo.getGoCity())) {
                return Result.error("起始点城市未开启");
            }
            if (!cityInfoService.isOpenCity(basicsVo.getToCity())) {
                return Result.error("目的地城市未开启");
            }
            //限制接单区域
            WMPoint wmPoint = new WMPoint();
            wmPoint.setLng(basicsVo.getGoLng());
            wmPoint.setLat(basicsVo.getGoLat());
            if (!banAreaService.isInBanArea(wmPoint, null)) {
                return Result.error("当前起始点不在服务范围内");
            }

            wmPoint.setLng(basicsVo.getGoLng());
            wmPoint.setLat(basicsVo.getGoLat());
            if (!banAreaService.isInBanArea(wmPoint, null)) {
                return Result.error("当前目的地不在服务范围内");
            }
        }
        CalculatePrice calculatePrice = new CalculatePrice();
        if (basicsVo.getMoneyType() == 1) {
            PackageTime packageTime = packageTimeService.getById(basicsVo.getTimeId());
            if (packageTime == null || packageTime.getIsEnable() != 1) {
                return Result.error("所选时间不存在或未启用");
            } else {

                Integer time;
                if (packageTime.getTimeUnit() == 1) {
                    time = packageTime.getTimeNum();
                } else if (packageTime.getTimeUnit() == 2) {
                    time = packageTime.getTimeNum() * 60;
                } else if (packageTime.getTimeUnit() == 3) {
                    time = packageTime.getTimeNum() * 60 * 24;
                } else {
                    return Result.error("时间配置参数异常,请联系管理员");
                }
                calculatePrice.setDuration(new BigDecimal(time));
                calculatePrice.setAllMoney(packageTime.getMoney());
                calculatePrice.setPayMoney(packageTime.getMoney());
            }
        } else {

            calculatePrice = new CalculatePrice();
            String isOpen = commonInfoService.findOne(422).getValue();
            if ("是".equals(isOpen)) {
                //一口价
                BanArea startArea = banAreaService.getAreaByPoint(basicsVo.getGoLng(), basicsVo.getGoLat());
                BanArea endArea = banAreaService.getAreaByPoint(basicsVo.getToLng(), basicsVo.getToLat());
                //如果不在同一区域内
                if (startArea == null || endArea == null || !startArea.getAreaId().equals(endArea.getAreaId())) {
                    //按照正常计费
                    calculatePrice = getCalculatePrice(basicsVo.getGoCity(), basicsVo.getGoDistrict(), basicsVo.getGoLng(), basicsVo.getGoLat(), basicsVo.getToLng(), basicsVo.getToLat(), basicsVo.getType());
                } else {
                    CalculatePrice price = getCalculatePrice(basicsVo.getGoCity(), basicsVo.getGoDistrict(), basicsVo.getGoLng(), basicsVo.getGoLat(), basicsVo.getToLng(), basicsVo.getToLat(), basicsVo.getType());
                    calculatePrice.setDuration(price.getDuration());
                    calculatePrice.setAllMoney(startArea.getBaseMoney());
                    calculatePrice.setPayMoney(startArea.getBaseMoney());
                }
            } else {
                //按照正常计费
                calculatePrice = getCalculatePrice(basicsVo.getGoCity(), basicsVo.getGoDistrict(), basicsVo.getGoLng(), basicsVo.getGoLat(), basicsVo.getToLng(), basicsVo.getToLat(), basicsVo.getType());
            }
        }

        //优惠券优惠
        //优惠券判断
        if (basicsVo.getCouponId() != null) {
            TbCouponUser tbCouponUser = couponUserService.getById(basicsVo.getCouponId());
            if (tbCouponUser == null) {
                return Result.error("你未持有当前优惠券");
            }
            if (tbCouponUser.getStatus() == 1) {
                return Result.error("当前优惠券已使用");
            }
            if (tbCouponUser.getStatus() == 2) {
                return Result.error("当前优惠券已失效");
            }
            //如果订单金额大于优惠券最小订单金额
            if (calculatePrice.getAllMoney().compareTo(tbCouponUser.getMinMoney()) >= 0) {
                calculatePrice.setRedPacketMoney(tbCouponUser.getMoney().setScale(2, RoundingMode.FLOOR));
                calculatePrice.setPayMoney(calculatePrice.getPayMoney().subtract(tbCouponUser.getMoney()).setScale(2, RoundingMode.FLOOR));
            } else {
                return Result.error("订单金额不满足最低满减金额");
            }
        }
        return Result.success().put("data", calculatePrice);
    }


    @Override
    public CalculatePrice getCalculatePrice(String goCity, String goDistrict, double goLng, double goLat, double toLng, double toLat, Integer type) {
        //起步价
        BigDecimal initMoney;
        //起步公里数
        BigDecimal initKilometer;
        //额外每公里价格
        BigDecimal unitOverMoney;
        //特殊时间段每公里费用（22:00~23:59）额外加价(单位:元)
        BigDecimal nightOtherMoney;
        //特殊时间段每公里费用（00:00~06:59）额外加价(单位:元)
        BigDecimal beforeDawnOtherMoney;
        //每分钟时长费
        BigDecimal durationMoney;

        CityInfo cityInfo = cityInfoService.getOne(new QueryWrapper<CityInfo>().eq("city_name", goCity));

        if (cityInfo.getAgentUserId() == null) {
            String[] split = commonInfoService.findOne(315).getValue().split(",");
            unitOverMoney = new BigDecimal(commonInfoService.findOne(316).getValue());
            initMoney = new BigDecimal(split[1]);
            initKilometer = new BigDecimal(split[0]);
            nightOtherMoney = new BigDecimal(commonInfoService.findOne(335).getValue());
            beforeDawnOtherMoney = new BigDecimal(commonInfoService.findOne(336).getValue());
            durationMoney = new BigDecimal(commonInfoService.findOne(351).getValue());
        } else {
            if (cityInfo.getBaseMoney() == null || cityInfo.getBaseMoney().compareTo(BigDecimal.ZERO) == 0) {
                String[] split = commonInfoService.findOne(315).getValue().split(",");
                initMoney = new BigDecimal(split[1]);
                initKilometer = new BigDecimal(split[0]);
            } else {
                initMoney = cityInfo.getBaseMoney();
                initKilometer = cityInfo.getBaseKilometres();
            }
            if (cityInfo.getUnitOverMoney() == null || cityInfo.getUnitOverMoney().compareTo(BigDecimal.ZERO) == 0) {
                unitOverMoney = new BigDecimal(commonInfoService.findOne(316).getValue());
            } else {
                unitOverMoney = cityInfo.getUnitOverMoney();
            }
            if (cityInfo.getUnitOverMoney() == null || cityInfo.getUnitOverMoney().compareTo(BigDecimal.ZERO) == 0) {
                nightOtherMoney = new BigDecimal(commonInfoService.findOne(335).getValue());
            } else {
                nightOtherMoney = cityInfo.getNightMoney();
            }
            if (cityInfo.getUnitOverMoney() == null || cityInfo.getUnitOverMoney().compareTo(BigDecimal.ZERO) == 0) {
                beforeDawnOtherMoney = new BigDecimal(commonInfoService.findOne(336).getValue());
            } else {
                beforeDawnOtherMoney = cityInfo.getEarlyMoney();
            }
            if (cityInfo.getUnitOverMoney() == null || cityInfo.getUnitOverMoney().compareTo(BigDecimal.ZERO) == 0) {
                durationMoney = new BigDecimal(commonInfoService.findOne(351).getValue());
            } else {
                durationMoney = cityInfo.getMinuteMoney();
            }
        }
        CalculatePrice calculatePrice = new CalculatePrice();
        //获取距离(米)
        TxDirection txDirection = getDistance(goLat, goLng, toLat, toLng, type);
        BigDecimal distance = txDirection.getDistance().divide(new BigDecimal("1000"), 2, RoundingMode.FLOOR);
        //最终价格
        BigDecimal allMoney = BigDecimal.ZERO;


        allMoney = allMoney.add(initMoney);
        //超出起步的公里数
        BigDecimal metre = distance.subtract(initKilometer);

        if (metre.compareTo(BigDecimal.ZERO) <= 0) {
            metre = BigDecimal.ZERO;
        }
        //超出起步公里数的总价格
        BigDecimal otherMoney = BigDecimal.ZERO;
        if ((distance.subtract(metre)).compareTo(BigDecimal.ZERO) > 0) {
            //是否是夜晚
            if (LocalTime.now().isAfter(LocalTime.of(22, 0)) && LocalTime.now().isBefore(LocalTime.of(23, 59))) {
                //每公里单价 = 每公里单价 + 特殊时段额外价格
                unitOverMoney = unitOverMoney.add(nightOtherMoney);
                calculatePrice.setIsNight(1);
            }
            //是否是凌晨
            if (LocalTime.now().isAfter(LocalTime.of(0, 0)) && LocalTime.now().isBefore(LocalTime.of(6, 59))) {
                //每公里单价 = 每公里单价 + 特殊时段额外价格
                unitOverMoney = unitOverMoney.add(beforeDawnOtherMoney);
                calculatePrice.setIsBeforeDawn(1);
            }
            //超出部分总费用 = 超出公里数 x 超出部分每公里单价
            otherMoney = metre.multiply(unitOverMoney);

            allMoney = allMoney.add(otherMoney);
        }
        //时长费
        BigDecimal durationAllMoney = durationMoney.multiply(txDirection.getDuration());

        allMoney = allMoney.add(durationAllMoney).setScale(2, RoundingMode.FLOOR);
        calculatePrice.setDistance(distance);
        calculatePrice.setKilometer(initKilometer);
        calculatePrice.setInitMoney(initMoney.setScale(2, RoundingMode.FLOOR));
        calculatePrice.setMetre(metre);
        calculatePrice.setPolyline(txDirection.getPolyline());
        calculatePrice.setDurationMoney(durationMoney.setScale(2, RoundingMode.FLOOR));
        calculatePrice.setUnitOverMoney(unitOverMoney.setScale(2, RoundingMode.FLOOR));
        calculatePrice.setOtherMoney(otherMoney.setScale(2, RoundingMode.FLOOR));
        calculatePrice.setDurationAllMoney(durationAllMoney.setScale(2, RoundingMode.FLOOR));
        calculatePrice.setAllMoney(allMoney.setScale(2, RoundingMode.FLOOR));
        calculatePrice.setPayMoney(allMoney.setScale(2, RoundingMode.FLOOR));
        calculatePrice.setType(type);
        calculatePrice.setDuration(txDirection.getDuration());
        return calculatePrice;
    }

    @Override
    public Result findComplaint(Long userId, Long complaintId, String indentNumber) {
        SysComplaint sysComplaint = indentDao.findComplaint(userId, complaintId, indentNumber);
        return Result.success().put("data", sysComplaint);
    }

    /**
     * 计算用户上级收益
     *
     * @param indentId 订单id
     * @param classify 1订单分成 2订单退款
     */
    @Override
    public void setCommission(Long indentId, Integer classify) {
        //计算用户上级收益
        Indent indent = indentDao.selectById(indentId);
        UserEntity userParent = userService.getOne(new QueryWrapper<UserEntity>().eq("user_id", indent.getUserScaleUserId()));
        if (userParent != null) {
            this.setIndentMoneyDetails(userParent, indent, indent.getUserScaleMoney(), 1, classify);
            UserEntity userParentParent = userService.getOne(new QueryWrapper<UserEntity>().eq("user_id", indent.getUserTwoUserId()));
            if (userParentParent != null) {
                this.setIndentMoneyDetails(userParentParent, indent, indent.getUserTwoMoney(), 2, classify);
            }
        }
    }

    /**
     * @param userEntity 用户id
     * @param indent     订单
     * @param type       1一级用户 2二级用户 3一级师傅 4二级师傅
     * @param classify   1订单分成 2订单退款
     */
    private void setIndentMoneyDetails(UserEntity userEntity, Indent indent, BigDecimal money, Integer type, Integer classify) {
        String title;
        //增加余额
        BigDecimal moneyDetails;
        if (classify == 1) {
            moneyDetails = userEntity.getBalance().add(money);
            title = "分成";
        } else {
            moneyDetails = userEntity.getBalance().subtract(money);
            title = "退款";
        }
        indentDao.updateRiderBalance(moneyDetails, userEntity.getUserId());
        //添加用户邀请人钱包详情
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        userMoneyDetails.setUserId(userEntity.getUserId());
        userMoneyDetails.setUserType(2);
        if (type == 1) {
            userMoneyDetails.setTitle("一级用户订单" + title);
            userMoneyDetails.setMoney(indent.getUserScaleMoney());
            userMoneyDetails.setContent("订单号:" + indent.getIndentNumber() + ",订单总价:" + indent.getAgentIndentMoney() + "," + title + "金额:" + indent.getUserScaleMoney());
            userMoneyDetails.setUserLevel(1);
            userMoneyDetails.setRelationId(indent.getUserId());
        } else if (type == 2) {
            userMoneyDetails.setTitle("二级用户订单" + title);
            userMoneyDetails.setMoney(indent.getUserTwoMoney());
            userMoneyDetails.setContent("订单号:" + indent.getIndentNumber() + ",订单总价:" + indent.getAgentIndentMoney() + "," + title + "金额:" + indent.getUserTwoMoney());
            userMoneyDetails.setRelationId(indent.getUserId());
            userMoneyDetails.setUserLevel(2);
        }
        userMoneyDetails.setType(1);
        userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        userMoneyDetails.setClassify(2);
        //app端用户消息推送
        userService.pushToSingle("订单分成", "订单号:" + indent.getIndentNumber() + ",订单总价:" + indent.getIndentMoney() + "," + title + "金额:" + indent.getUserScaleMoney(), userEntity.getClientid());
        userMoneyDetailsService.save(userMoneyDetails);
    }

    @Override
    public Result riderDelivery(Long userId, String indentId) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            Indent indent = indentDao.selectById(indentId);
            if (indent.getIndentState() == 3) {
                return Result.error("订单已完成");
            }

            indent.setIndentState(3);
            indent.setFinishTime(LocalDateTime.now());
            Duration userHours = Duration.between(indent.getStartTime(), indent.getFinishTime());
            indent.setRealDuration(new BigDecimal(userHours.toMinutes()));

            BigDecimal durationMoney;
            BigDecimal baseMoney;

            CityInfo cityInfo = cityInfoService.getOne(new QueryWrapper<CityInfo>().eq("city_name", indent.getShipCity()));
            if (cityInfo.getAgentUserId() == null) {
                durationMoney = new BigDecimal(commonInfoService.findOne(351).getValue());
                baseMoney = new BigDecimal(commonInfoService.findOne(315).getValue().split(",")[1]);
            } else {
                durationMoney = cityInfo.getMinuteMoney();
                baseMoney = cityInfo.getBaseMoney();
            }

            BigDecimal indentMoney;
            BigDecimal subtractMoney;

            if (indent.getMoneyType() == 1 || indent.getAreaId()!=null) {
                if (indent.getAreaId() == null) {
                    //包时价格
                    indentMoney = indent.getIndentBasicsMoney().add(indent.getWaitMoney());
                    indent.setIndentMoney(indentMoney);
                } else {
                    BanArea banArea = banAreaService.getById(indent.getAreaId());
                    indentMoney = banArea.getBaseMoney().add(indent.getWaitMoney());
                    indent.setIndentMoney(indentMoney);
                }

            } else {
                //时长收费
                if (indent.getDuration() != null) {
                    subtractMoney = indent.getIndentBasicsMoney().subtract(indent.getDuration().multiply(durationMoney)).setScale(2, RoundingMode.FLOOR);

                } else {
                    subtractMoney = indent.getIndentBasicsMoney();
                }
                //实际时长费
                BigDecimal realMoney = indent.getRealDuration().multiply(durationMoney);
                //支付金额=总金额+实际时长费
                indentMoney = subtractMoney.add(realMoney).setScale(2, RoundingMode.FLOOR);

                if (indentMoney.compareTo(baseMoney) < 0) {
                    indentMoney = baseMoney;
                }
                indent.setIndentMoney(indentMoney.add(indent.getWaitMoney()));
                JSONObject jsonObject = JSONObject.parseObject(indent.getMoneyJson());
                if (jsonObject != null) {
                    CalculatePrice calculatePrice = jsonObject.toJavaObject(CalculatePrice.class);
                    calculatePrice.setDuration(new BigDecimal(userHours.toMinutes()));
                    calculatePrice.setDurationAllMoney(realMoney);
                    calculatePrice.setPayMoney(indentMoney);



                    indent.setMoneyJson(JSON.toJSONString(calculatePrice));
                }

            }

            UserEntity riderEntity = userService.getById(indent.getRiderUserId());
            if (indent.getCouponId() != null) {
                TbCouponUser couponUser = couponUserService.getById(indent.getCouponId());
                //如果订单金额大于优惠券最小订单金额
                if (indent.getIndentMoney().compareTo(couponUser.getMinMoney()) >= 0) {
                    indent.setCouponMoney(couponUser.getMoney());

                    BigDecimal moneySubCouponMoney = indent.getIndentMoney().subtract(couponUser.getMoney()).setScale(2, RoundingMode.FLOOR);
                    if (moneySubCouponMoney.compareTo(BigDecimal.ZERO) <= 0) {
                        indent.setIndentMoney(new BigDecimal("0.01"));
                    } else {
                        indent.setIndentMoney(moneySubCouponMoney);
                    }

                } else {
                    //如果实际价格不到优惠券使用价格则返还优惠券
                    if (indent.getUserId() != null) {
                        couponUser.setStatus(0);
                        couponUserService.updateById(couponUser);
                        indent.setCouponId(null);
                        indent.setCouponMoney(null);
                        MessageInfo messageInfo = new MessageInfo();
                        messageInfo.setUserId(indent.getUserId().toString());
                        messageInfo.setTitle("优惠券返还提醒");
                        messageInfo.setContent("您的订单" + indent.getIndentNumber() + "由于实际价格" + indent.getIndentMoney() + "不满足优惠券使用最低金额" + couponUser.getMinMoney() + "优惠券已返还");
                        messageInfo.setState("5");
                        messageInfo.setCreateAt(DateUtils.format(new Date()));
                        messageInfo.setIsSee("0");
                        messageService.save(messageInfo);
                    }
                }
            }
            //平台收入
            BigDecimal pingMoney = indentMoney;
            //代理商收入
            BigDecimal agentMoney = BigDecimal.ZERO;

            if (cityInfo.getAgentUserId() == null) {
                //根据实际支付价格算出实际师傅佣金
                indent.setRiderMoney(indentMoney.multiply(new BigDecimal(riderEntity.getRate())).setScale(2, RoundingMode.FLOOR));
                indent=setReward(indent);
                //写入上级及分成金额
                if (indent.getUserId() != null) {
                    indent=updateIndentRateMoney(indent, indent.getUserId());
                }
                //平台收入减去师傅佣金
                pingMoney = pingMoney.subtract(indent.getRiderMoney());
                //平台减去推广费用
                if (indent.getUserScaleMoney() != null && indent.getUserScaleMoney().compareTo(BigDecimal.ZERO) > 0) {
                    pingMoney = pingMoney.subtract(indent.getUserScaleMoney());
                }
                if (indent.getUserTwoMoney() != null && indent.getUserTwoMoney().compareTo(BigDecimal.ZERO) > 0) {
                    pingMoney = pingMoney.subtract(indent.getUserTwoMoney());
                }
            } else {
                //根据比例算出平台收入
                pingMoney = indentMoney.multiply(indent.getPingRate());
                //剩下金额全部算到代理城市
                indent.setAgentIndentMoney(indent.getIndentMoney().subtract(pingMoney));
                //计算师傅佣金
                indent.setRiderMoney(indentMoney.multiply(new BigDecimal(riderEntity.getRate())).setScale(2, RoundingMode.FLOOR));

                //代理收入  = 代理城市 - 师傅佣金 - 一级推广 - 二级推广
                agentMoney = indent.getAgentIndentMoney().subtract(indent.getRiderMoney());
                //写入上级及分成金额
                if (indent.getUserId() != null) {
                    indent=updateIndentRateMoney(indent, indent.getUserId());
                }
                if (indent.getUserScaleMoney() != null && indent.getUserScaleMoney().compareTo(BigDecimal.ZERO) > 0) {
                    agentMoney = agentMoney.subtract(indent.getUserScaleMoney());
                }
                if (indent.getUserTwoMoney() != null && indent.getUserTwoMoney().compareTo(BigDecimal.ZERO) > 0) {
                    agentMoney = agentMoney.subtract(indent.getUserTwoMoney());
                }
            }
            indent.setPlatformMoney(pingMoney);
            indent.setAgentMoney(agentMoney);
            indent.setEstimateMoney(indent.getIndentMoney());
            indentDao.updateById(indent);

            //给用户付款发送通知
            if (indent.getUserId() != null) {
                List<String> msgList = new ArrayList<>();

                msgList.add(0, indent.getIndentNumber());
                String address = indent.getShipAddress() + "" + indent.getDeliveryAddress();
                if (address.length() >= 20) {
                    address = address.substring(0, 15) + "...";
                }
                msgList.add(1, address);
                msgList.add(2, "待付款");
                msgList.add(3, "师傅已送达,请及时付款");
                CommonInfo userNotice = commonInfoService.findOne(307);
                CommonInfo riderNotice = commonInfoService.findOne(268);

                UserEntity userEntity = userService.getById(indent.getUserId());

                if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                    SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), userNotice.getValue(), msgList, 1);
                }
                msgList.add(3, "订单待付款,收入:" + indent.getRiderMoney().setScale(2, RoundingMode.FLOOR));

                if (StringUtils.isNotEmpty(riderEntity.getRiderOpenId())) {
                    SenInfoCheckUtil.sendRiderMsg(userEntity.getRiderOpenId(), riderNotice.getValue(), msgList, 1);
                }

                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setState(String.valueOf(4));
                messageInfo.setContent("师傅已将您送达指定位置,请及时付款");
                messageInfo.setTitle("订单已完成");
                messageInfo.setUserName(userEntity.getNickName());
                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date now = new Date();
                messageInfo.setCreateAt(sdf.format(now));
                messageInfo.setIsSee("0");
                messageService.save(messageInfo);
            }
            return Result.success();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("师傅完成订单异常：" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    public Indent setReward(Indent indent) {
        UserEntity userEntity = userService.getById(indent.getRiderUserId());
        if (userEntity.getIsEnableReward() != null && userEntity.getIsEnableReward() == 1) {
            //获取今天完成的数量
            Integer count = baseMapper.getNowBeforeCount(indent.getRiderUserId(), LocalDateTime.now());
            Reward reward = rewardService.getOne(new QueryWrapper<Reward>().eq("num", count + 1).eq("is_enable", 1));
            if (reward != null) {

                indent.setRiderRewardMoney(indent.getRiderMoney().multiply(reward.getRewardProp()));
            }
        }
        return indent;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addIndentBuy(Indent indent) {

        String value = commonInfoService.findOne(371).getValue();
        if (indent.getAddType() == 1) {
            Integer count = indentDao.selectCount(new QueryWrapper<Indent>().eq("indent_state", 3).eq("user_id", indent.getUserId()));
            if (count > 0) {
                return Result.error("尚有未支付的订单,请先支付");
            }

            Integer haveCount = indentDao.selectCount(new QueryWrapper<Indent>().in("indent_state", 0, 1, 2).eq("user_id", indent.getUserId()));
            if (haveCount > 0) {
                return Result.error("当前有正在进行中的订单,请先取消");
            }
            UserEntity userEntity = userService.getById(indent.getUserId());
            if (StringUtils.isBlank(indent.getCustomName())) {
                indent.setCustomName(userEntity.getUserName());
            }
            if (StringUtils.isBlank(indent.getCustomPhone())) {
                indent.setCustomPhone(userEntity.getPhone());
            }
            int minScore = Integer.parseInt(commonInfoService.findOne(365).getValue());
            if (userEntity.getCreditScore() < minScore) {
                return Result.error("信用分不足无法下单,请联系管理员");
            }
            indent.setShipUserName(userEntity.getNickName());
            indent.setShipUserPhone(userEntity.getPhone());
        }
        CityInfo cityInfo = cityInfoService.getOne(new QueryWrapper<CityInfo>().eq("city_name", indent.getShipCity()));
        indent.setCityId(cityInfo.getId());
        indent.setPingRate(cityInfo.getPingRate());
        if (indent.getShipAddressId() != null) {
            //出发地址
            SysUserAddress shipAddress = userAddressService.getById(indent.getShipAddressId());
            if (shipAddress == null) {
                return Result.error("出发地址不存在");
            }
            indent.setShipProvince(shipAddress.getProvince());
            indent.setShipCity(shipAddress.getCity());
            indent.setShipDistrict(shipAddress.getCounty());
            indent.setShipAddress(shipAddress.getAddress());
            indent.setShipAddressLongitude(shipAddress.getLng());
            indent.setShipAddressLatitude(shipAddress.getLat());
        }
        //目的地址
        if (indent.getDeliveryAddressId() != null) {
            SysUserAddress deliveryAddress = userAddressService.getById(indent.getDeliveryAddressId());
            if (deliveryAddress == null) {
                return Result.error("目的地址不存在");
            }
            indent.setDeliveryProvince(deliveryAddress.getProvince());
            indent.setDeliveryCity(deliveryAddress.getCity());
            indent.setDeliveryDistrict(deliveryAddress.getCounty());
            indent.setDeliveryAddress(deliveryAddress.getAddress());
            indent.setDeliveryAddressLongitude(deliveryAddress.getLng());
            indent.setDeliveryAddressLatitude(deliveryAddress.getLat());
        }
        //是否开启检测限制区域下单和城市是否开通
        if ("是".equals(value)) {
            if (!cityInfoService.isOpenCity(indent.getShipDistrict())) {
                return Result.error("起始点城市未开启");
            }
            if (!cityInfoService.isOpenCity(indent.getDeliveryDistrict())) {
                return Result.error("目的地城市未开启");
            }
            //限制接单区域
            WMPoint wmPoint = new WMPoint();
            wmPoint.setLng(indent.getShipAddressLongitude());
            wmPoint.setLat(indent.getShipAddressLatitude());
            if (!banAreaService.isInBanArea(wmPoint, null)) {
                return Result.error("当前起始点不在服务区内");
            }

            wmPoint.setLng(indent.getDeliveryAddressLongitude());
            wmPoint.setLat(indent.getDeliveryAddressLatitude());
            if (!banAreaService.isInBanArea(wmPoint, null)) {
                return Result.error("当前目的地不在服务区内");
            }
        }

        //计算价格
        indent.setCreateTime(LocalDateTime.now());
        indent.setIndentNumber(generateOrder());
        indent.setIndentState(0);

        if (indent.getMoneyType() == 1) {
            //包时
            PackageTime packageTime = packageTimeService.getById(indent.getTimeId());
            if (packageTime == null || packageTime.getIsEnable() != 1) {
                return Result.error("所选时间不存在或未启用");
            } else {
                Integer time;
                if (packageTime.getTimeUnit() == 1) {
                    time = packageTime.getTimeNum();
                } else if (packageTime.getTimeUnit() == 2) {
                    time = packageTime.getTimeNum() * 60;
                } else if (packageTime.getTimeUnit() == 3) {
                    time = packageTime.getTimeNum() * 60 * 24;
                } else {
                    return Result.error("时间配置参数异常,请联系管理员");
                }
                CalculatePrice calculatePrice = getCalculatePrice(indent.getShipCity(), indent.getShipDistrict(), indent.getShipAddressLongitude(), indent.getShipAddressLatitude(), indent.getDeliveryAddressLongitude(), indent.getDeliveryAddressLatitude(), indent.getType());
                indent.setDistance(calculatePrice.getDistance());
                indent.setTimeNum(time);
                indent.setEstimateMoney(packageTime.getMoney());
                indent.setIndentBasicsMoney(packageTime.getMoney());
                indent.setIndentMoney(packageTime.getMoney());
                indent.setMoneyJson(JSON.toJSONString(calculatePrice));
            }
        } else {
            //一口价
            String isOpen = commonInfoService.findOne(422).getValue();
            if ("是".equals(isOpen)) {
                BanArea startArea = banAreaService.getAreaByPoint(indent.getShipAddressLongitude(), indent.getShipAddressLatitude());
                BanArea endArea = banAreaService.getAreaByPoint(indent.getDeliveryAddressLongitude(), indent.getDeliveryAddressLatitude());
                //如果不在同一区域内
                if (startArea == null || endArea == null || !startArea.getAreaId().equals(endArea.getAreaId())) {
                    //按照正常计费
                    indent=setEstimateMoney(indent);
                } else {
                    CalculatePrice calculatePrice = getCalculatePrice(indent.getShipCity(), indent.getShipDistrict(), indent.getShipAddressLongitude(), indent.getShipAddressLatitude(), indent.getDeliveryAddressLongitude(), indent.getDeliveryAddressLatitude(), indent.getType());
                    indent.setDistance(calculatePrice.getDistance());
                    indent.setDuration(calculatePrice.getDuration());
                    indent.setEstimateMoney(startArea.getBaseMoney());
                    indent.setIndentBasicsMoney(startArea.getBaseMoney());
                    indent.setAreaId(startArea.getAreaId());
                    indent.setMoneyJson(JSON.toJSONString(calculatePrice));
                }
            } else {
                //按照正常计费
                indent=setEstimateMoney(indent);
            }
        }

        if (indent.getCouponId() != null) {
            TbCouponUser tbCouponUser = couponUserService.getById(indent.getCouponId());
            if (tbCouponUser == null) {
                return Result.error("未持有当前优惠券");
            }
            if (tbCouponUser.getStatus() == 1) {
                return Result.error("当前优惠券已使用");
            }
            if (tbCouponUser.getStatus() == 2) {
                return Result.error("当前优惠券已失效");
            }
            //如果订单金额大于优惠券最小订单金额
            if (indent.getIndentBasicsMoney().compareTo(tbCouponUser.getMinMoney()) >= 0) {
                indent.setEstimateMoney(indent.getIndentBasicsMoney().subtract(tbCouponUser.getMoney()));
                tbCouponUser.setStatus(1);
                indent.setCouponMoney(tbCouponUser.getMoney());
                couponUserService.updateById(tbCouponUser);
            } else {
                return Result.error("订单金额不满足最低满减金额");
            }
        }
        //如果已有师傅订单,则直接给师傅。
        if (indent.getRiderUserId() != null) {


            UserEntity riderUser = userService.getById(indent.getRiderUserId());
            if (riderUser == null) {
                return Result.error("师傅不存在！");
            }
            if (StringUtils.isBlank(riderUser.getCheckCertification()) || !"1".equals(riderUser.getCheckCertification())) {
                return Result.error("师傅尚未通过实名认证");
            }
            if (riderUser.getStatus() != 1) {
                return Result.error("该帐号已被封禁");
            }
            CommonInfo one1 = commonInfoService.findOne(261);
            Double cashDeposit = Double.parseDouble(one1.getValue());
            if (riderUser.getCashDeposit().doubleValue() < cashDeposit) {
                return Result.error("师傅保证金不足！");
            }
            indent.setIndentState(1);
            CommonInfo riderTemp = commonInfoService.findOne(268);
            List<String> msgList = new ArrayList<>();
            msgList.add(0, indent.getIndentNumber());
            String address = indent.getShipAddress() + "" + indent.getDeliveryAddress();
            if (address.length() >= 20) {
                address = address.substring(0, 15) + "...";
            }
            msgList.add(1, address);
            msgList.add(2, "已接单");
            msgList.add(3, "你有一条新订单");
            if (StringUtils.isNotEmpty(riderUser.getRiderOpenId())) {
                SenInfoCheckUtil.sendRiderMsg(riderUser.getRiderOpenId(), riderTemp.getValue(), msgList, 1);
            }
        }
        return Result.upStatus(baseMapper.insert(indent));
    }

    private Indent setEstimateMoney(Indent indent) {
        CalculatePrice calculatePrice = getCalculatePrice(indent.getShipCity(), indent.getShipDistrict(), indent.getShipAddressLongitude(), indent.getShipAddressLatitude(), indent.getDeliveryAddressLongitude(), indent.getDeliveryAddressLatitude(), indent.getType());
        indent.setDistance(calculatePrice.getDistance());
        indent.setDuration(calculatePrice.getDuration());
        indent.setIndentBasicsMoney(calculatePrice.getAllMoney());
        indent.setEstimateMoney(calculatePrice.getPayMoney());
        indent.setIsNight(calculatePrice.getIsNight());
        indent.setIsBeforeDawn(calculatePrice.getIsBeforeDawn());
        indent.setPolyline(calculatePrice.getPolyline());
        calculatePrice.setPolyline(null);
        indent.setMoneyJson(JSON.toJSONString(calculatePrice));
        return indent;
    }

    @Override
    public IPage<Indent> findNewIndent(Long userId, Integer page, Integer limit, Double ol, Double od, Indent indent) {
        Page<Indent> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        String range = commonInfoService.findOne(372).getValue();
        IPage<Indent> newIndent = baseMapper.findNewIndent(pages, ol, od, range, indent);
        for (Indent record : newIndent.getRecords()) {
            UserEntity userEntity = userService.getById(userId);
            //CityInfo cityInfo = cityInfoService.getOne(new QueryWrapper<CityInfo>().eq("id", record.getCityId()));
            //BigDecimal rateRate;
            //扣除平台分成后的价格
            /*if (cityInfo != null) {
                rateRate = cityInfo.getPingRate();
            } else {
                rateRate = new BigDecimal(userEntity.getRate());
            }*/
//            BigDecimal agentMoney = record.getEstimateMoney().subtract(record.getEstimateMoney().multiply(rateRate));

            record.setRiderMoney(record.getEstimateMoney().multiply(new BigDecimal(userEntity.getRate())).setScale(2, RoundingMode.FLOOR));
        }
        return newIndent;

    }


    @Override
    public IPage<Indent> findUserIndent(Integer page, Integer limit, Indent indent) {
        Page<Indent> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.selectPage(pages, new QueryWrapper<>(indent).orderByDesc("create_time"));

    }


    @Override
    public Result findVicinityRider(Double lng, Double lat) {
        HashMap<String, Object> hashMap = new HashMap<>();
        if (lng != null && lat != null) {
            CommonInfo commonInfo = commonInfoService.findOne(349);
            List<RiderVo> kmRider = indentDao.findVicinityRider(lng, lat, commonInfo.getValue());
            hashMap.put("kmRider", kmRider);
            hashMap.put("count", kmRider.size());
        }
        return Result.success().put("data", hashMap);
    }

    @Override
    public IPage<Indent> getIndentList(Integer page, Integer limit, Long userId, Integer indentType, String indentNumber, String startTime, String endTime) {
        Page<Indent> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return indentDao.getIndentList(pages, userId, indentType, indentNumber, startTime, endTime);
    }

    @Override
    public BigDecimal getOneProfit(Long userId, int level) {

        return indentDao.getOneProfit(userId, level);

    }

    @Override
    public Result distributionOrder(Long indentId, Long userId) {
        Indent indent = indentDao.selectById(indentId);
        UserEntity userEntity = userService.getById(indent.getUserId());
        UserEntity riderUser = userService.getById(userId);
        if (riderUser == null) {
            return Result.error("用户不存在！");
        }
        if (StringUtils.isBlank(riderUser.getCheckCertification()) || !"1".equals(riderUser.getCheckCertification())) {
            return Result.error("该用户尚未通过实名认证");
        }
        if (riderUser.getStatus() != 1) {
            return Result.error("该帐号已被封禁");
        }
        CommonInfo one1 = commonInfoService.findOne(261);
        Double cashDeposit = Double.parseDouble(one1.getValue());
        if (riderUser.getCashDeposit().doubleValue() < cashDeposit) {
            return Result.error("师傅保证金不足！");
        }
        indent.setRiderUserId(riderUser.getUserId());
        indent.setIsTransfer(1);
        indent.setReceivingTime(LocalDateTime.now());
        indent.setIndentState(1);
        baseMapper.updateById(indent);
        CommonInfo userTemp = commonInfoService.findOne(307);
        CommonInfo riderTemp = commonInfoService.findOne(268);
        List<String> msgList = new ArrayList<>();
        msgList.add(0, indent.getIndentNumber());
        String address = indent.getShipAddress() + "" + indent.getDeliveryAddress();
        if (address.length() >= 20) {
            address = address.substring(0, 15) + "...";
        }
        msgList.add(1, address);
        msgList.add(2, "已接单");
        msgList.add(3, "师傅已接单,正在赶来的路上");
        if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), userTemp.getValue(), msgList, 1);
        }
        if (StringUtils.isNotEmpty(riderUser.getRiderOpenId())) {
            SenInfoCheckUtil.sendRiderMsg(riderUser.getRiderOpenId(), riderTemp.getValue(), msgList, 1);
        }
        return Result.success();
    }

    @Override
    public IPage<HashMap<String, Object>> getProfitList(Integer page, Integer limit, String time, Integer flag) {
        Page<HashMap<String, Object>> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return indentDao.getProfitList(pages, time, flag);
    }

    @Override
    public Result indentReceiving(Long userId, String indentNumber) {
        //判断师傅状态是否被封号
        UserEntity riderUser = userService.getById(userId);
        Integer count = indentDao.selectCount(new QueryWrapper<Indent>().eq("rider_user_id", userId).in("indent_state", 1, 2));
        if (count > 0) {
            return Result.error("你当前还有未完成的订单,无法抢单");
        }
        reentrantReadWriteLock.writeLock().lock();
        try {
            int minScore = Integer.parseInt(commonInfoService.findOne(365).getValue());
            if (riderUser.getCreditScore() < minScore) {
                return Result.error("信用分不足无法接单,请联系管理员");
            }
            if (riderUser.getStatus() != 1) {
                return Result.error("您的帐号已被封禁，请联系客服解封！");
            }
            CommonInfo safetyMoney = commonInfoService.findOne(261);
            if (riderUser.getCashDeposit().compareTo(new BigDecimal(safetyMoney.getValue())) < 0) {
                return Result.error("你的保证金不足，请缴纳保证金后再接单");
            }
            if (riderUser.getOnLineFlag() != 1) {
                return Result.error("请先上线");
            }
            Indent indent = indentDao.findIndentByNumber(indentNumber);
            if (indent.getIndentState() != 0) {
                return Result.error("订单已被抢走！");
            }
            indent.setRiderUserId(userId);
            indent.setIndentState(1);
            indent.setReceivingTime(LocalDateTime.now());

            indent.setRiderMoney(indent.getEstimateMoney().multiply(new BigDecimal(riderUser.getRate())));


            UserEntity userEntity = userService.getById(indent.getUserId());
            CommonInfo userNotice = commonInfoService.findOne(307);
            CommonInfo riderNotice = commonInfoService.findOne(268);
            List<String> msgList = new ArrayList<>();
            msgList.add(0, indent.getIndentNumber());
            String address = indent.getShipAddress() + "" + indent.getDeliveryAddress();
            if (address.length() >= 20) {
                address = address.substring(0, 15) + "...";
            }
            msgList.add(1, address);
            msgList.add(2, "已接单");
            msgList.add(3, "接单成功，请尽快前往起始地点");

            //给师傅的通知
            if (StringUtils.isNotEmpty(riderUser.getRiderOpenId())) {
                SenInfoCheckUtil.sendRiderMsg(riderUser.getRiderOpenId(), riderNotice.getValue(), msgList, 1);
            }
            msgList.add(3, "师傅正在赶来的路上");
            //给用户的通知
            if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), userNotice.getValue(), msgList, 1);
            }
            //app推送
            //app端用户消息推送
            if (StringUtils.isNotEmpty(userEntity.getClientid())) {

                String contents = "您的订单已被师傅接单，正在赶来的路上";
                userService.pushToSingle("接单通知", contents, userEntity.getClientid());
            }
            //app端师傅消息推送
            if (StringUtils.isNotEmpty(riderUser.getClientRiderId())) {
                String contents = "接单成功，请尽快前往起始地点";
                userService.pushToSingleQiShou("接单通知", contents, riderUser.getClientRiderId());
            }
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState(String.valueOf(4));
            messageInfo.setContent("您的订单已被师傅接单，正在赶来的路上");
            messageInfo.setTitle("接单成功");
            messageInfo.setUserName(userEntity.getNickName());
            messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = new Date();
            messageInfo.setCreateAt(sdf.format(now));
            messageInfo.setIsSee("0");
            messageService.save(messageInfo);
            //计算师傅取消订单要扣除的违约金
            CommonInfo riderOne = commonInfoService.findOne(237);
            String valueRider = riderOne.getValue();
            BigDecimal riderFine = indent.getRiderMoney().multiply(new BigDecimal(valueRider)).setScale(2, RoundingMode.HALF_DOWN);
            indent.setRiderFine(riderFine);
            return Result.upStatus(indentDao.updateById(indent));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("师傅接单异常：" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    /**
     * 师傅接单后添加上级佣金比例
     *
     * @param indent
     * @param userId
     */
    public Indent updateIndentRateMoney(Indent indent, Long userId) {
        UserEntity userEntity = userService.getById(userId);
        //一级抽佣金额
        BigDecimal userScaleMoney;
        //二级抽佣金额
        BigDecimal userScaleTwoMoney;
        //计算用户上级收益。
        UserEntity parentBuyerUser = userService.getOne(new QueryWrapper<UserEntity>().eq("invitation_code", userEntity.getInviterCode()));
        if (parentBuyerUser != null) {
            BigDecimal rateMoney;
            rateMoney = indent.getIndentMoney();
            if (StringUtils.isNotEmpty(parentBuyerUser.getDivideScale())) {
                userScaleMoney = rateMoney.multiply(new BigDecimal(parentBuyerUser.getDivideScale()));
                indent.setUserScaleMoney(userScaleMoney);
                indent.setUserScaleUserId(parentBuyerUser.getUserId());
            }

            //上上级收益
            UserEntity parentParentBuyerUser = userService.getOne(new QueryWrapper<UserEntity>().eq("invitation_code", parentBuyerUser.getInviterCode()));
            if (parentParentBuyerUser != null) {
                if (StringUtils.isNotEmpty(parentParentBuyerUser.getDivideTwoScale())) {
                    userScaleTwoMoney = rateMoney.multiply(new BigDecimal(parentParentBuyerUser.getDivideTwoScale()));
                    indent.setUserTwoMoney(userScaleTwoMoney);
                    indent.setUserTwoUserId(parentParentBuyerUser.getUserId());
                }
            }
        }
        return indent;
    }


    @Override
    public IPage<Indent> getRiderIndentList(Long userId, Integer page, Integer limit, String indentState) {

        Page<Indent> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        UserEntity userEntity = userService.getById(userId);
        IPage<Indent> riderIndentList = baseMapper.getRiderIndentList(pages, userId, indentState);
        for (Indent record : riderIndentList.getRecords()) {
            //获取师傅离起始位置的距离
            RiderLocation location = locationService.getOne(new QueryWrapper<RiderLocation>().eq("user_id", record.getRiderUserId()));
            if (location != null) {
                if (record.getIndentState() == 1 && location.getLat() != null && location.getLng() != null) {
                    BigDecimal distance = getDistance(location.getLat(), location.getLng(), record.getShipAddressLatitude(), record.getShipAddressLongitude(), 4).getDistance();
                    record.setRiderDistance(distance);
                    //获取师傅离终点的距离
                } else if (record.getIndentState() == 2 && location.getLat() != null && location.getLng() != null) {
                    BigDecimal distance = getDistance(location.getLat(), location.getLng(), record.getDeliveryAddressLatitude(), record.getDeliveryAddressLongitude(), 1).getDistance();
                    record.setRiderDistance(distance);
                }
            }
            // 1已接单 2进行中的订单由于路程没走完,所以使用预估价格乘佣金比例
            if (record.getIndentState() == 1 || record.getIndentState() == 2) {
                CityInfo cityInfo = cityInfoService.getById(record.getCityId());
                //扣除平台分成后的价格
                //BigDecimal agentMoney = record.getEstimateMoney().subtract(record.getEstimateMoney().multiply(cityInfo.getPingRate()));

                record.setRiderMoney(record.getEstimateMoney().multiply(new BigDecimal(userEntity.getRate())).setScale(2, RoundingMode.FLOOR));
            }
        }
        return riderIndentList;
    }

    @Override
    public Result riderStartDrive(Long userId, Long indentId) {
        Indent indent = indentDao.selectById(indentId);
        indent.setStartTime(LocalDateTime.now());
        indent.setIndentState(2);
        if (indent.getUserId() != null) {
            CommonInfo userNotice = commonInfoService.findOne(307);
            List<String> msgList = new ArrayList<>();
            msgList.add(0, indent.getIndentNumber());
            String address = indent.getShipAddress() + "" + indent.getDeliveryAddress();
            if (address.length() >= 20) {
                address = address.substring(0, 15) + "...";
            }
            msgList.add(1, address);
            msgList.add(2, "开始服务");
            msgList.add(3, "正在前往目的地");

            UserEntity userEntity = userService.getById(indent.getUserId());
            //给用户的通知
            if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), userNotice.getValue(), msgList, 1);
            }
        }


        if (indent.getStartWaitTime() != null) {
            indent.setEndWaitTime(LocalDateTime.now());
            CityInfo cityInfo = cityInfoService.getById(indent.getCityId());
            Duration between = Duration.between(indent.getStartWaitTime(), indent.getEndWaitTime());
            //免费等待时长
            int freeWaitTime = Integer.parseInt(commonInfoService.findOne(423).getValue());

            //等待每分钟价格(单位:元)
            BigDecimal waitMinuteMoney = new BigDecimal(commonInfoService.findOne(424).getValue());
            //超时总金额
            BigDecimal waitMoney;
            if (cityInfo.getAgentUserId() != null) {
                if (cityInfo.getFreeWaitTime() != null && cityInfo.getWaitMinuteMoney() != null) {
                    freeWaitTime = cityInfo.getFreeWaitTime();
                    waitMinuteMoney = cityInfo.getWaitMinuteMoney();
                }
            }
            indent.setWaitTime((int) between.toMinutes());
            indent.setFreeWaitTime(freeWaitTime);
            long time = 0;
            if (freeWaitTime < between.toMinutes()) {
                time = between.toMinutes() - freeWaitTime;
            }
            if (time > 0) {
                waitMoney = waitMinuteMoney.multiply(new BigDecimal(time)).setScale(2, RoundingMode.FLOOR);
                indent.setWaitMoney(waitMoney);
            }
        }
        return Result.upStatus(baseMapper.updateById(indent));

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result indentPayCallback(Long indentId, Integer classify, BigDecimal payMoney) {
        Indent indent = indentDao.selectById(indentId);
        //给上级增加钱包余额
        setCommission(indentId, 1);
        if (classify == 0) {
            indent.setModeOfPayment("0");
        } else if (classify == 1 || classify == 2 || classify == 3 || classify == 6) {
            indent.setModeOfPayment("1");
        } else if (classify == 4 || classify == 5) {
            indent.setModeOfPayment("2");
        }
        indent.setIndentState(4);
        indentDao.updateById(indent);

        UserEntity userEntity = userService.getById(indent.getUserId());
        UserEntity riderEntity = userService.selectUserById(indent.getRiderUserId());

        BigDecimal balance = indent.getRiderMoney().add(indent.getRiderRewardMoney()).setScale(2, RoundingMode.FLOOR);
        //师傅收入
        riderEntity.setBalance(riderEntity.getBalance().add(balance));
        userService.updateById(riderEntity);

        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        userMoneyDetails.setUserType(1);
        //用户钱包明细
        userMoneyDetails.setMoney(indent.getIndentMoney().setScale(2, RoundingMode.FLOOR));
        userMoneyDetails.setUserId(indent.getUserId());
        userMoneyDetails.setType(2);
        String title = "";
        if (classify == 0) {
            title = "余额支付";
        } else if (classify == 1 || classify == 2 || classify == 3 || classify == 6) {
            title = "微信支付";
        } else if (classify == 4 || classify == 5) {
            title = "支付宝支付";
        }
        userMoneyDetails.setTitle(title);
        userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
        userMoneyDetails.setContent("支付订单号" + indent.getIndentNumber() + "共" + indent.getIndentMoney().setScale(2, RoundingMode.FLOOR) + "元");
        //将接单明细添加到钱包明细表里
        userMoneyDetailsService.save(userMoneyDetails);

        //师傅钱包明细
        userMoneyDetails.setMoney(balance);
        userMoneyDetails.setUserType(2);
        userMoneyDetails.setUserId(riderEntity.getUserId());
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("订单金额").append(indent.getIndentMoney().setScale(2, RoundingMode.FLOOR));
        if(indent.getAgentMoney()!=null && indent.getAgentMoney().doubleValue()>0){
            stringBuilder.append("，代理金额：").append(indent.getAgentMoney().setScale(2, RoundingMode.FLOOR));
        }
        if(indent.getUserScaleMoney()!=null && indent.getUserScaleMoney().doubleValue()>0){
            stringBuilder.append("，一级推广金额：").append(indent.getUserScaleMoney().setScale(2, RoundingMode.FLOOR));
        }
        if(indent.getUserTwoMoney()!=null && indent.getUserTwoMoney().doubleValue()>0){
            stringBuilder.append("，二级推广金额：").append(indent.getUserTwoMoney().setScale(2, RoundingMode.FLOOR));
        }
        stringBuilder.append("，平台服务费:").append(indent.getPlatformMoney().setScale(2, RoundingMode.FLOOR)).append("元,收入").append(balance).append("元");
        if (indent.getRiderRewardMoney() != null && indent.getRiderRewardMoney().compareTo(BigDecimal.ZERO) > 0) {
            stringBuilder.append("元，其中新人奖励金额:").append(indent.getRiderRewardMoney().setScale(2, RoundingMode.FLOOR)).append("元");
        }
        userMoneyDetails.setContent(stringBuilder.toString());
        userMoneyDetails.setTitle("订单编号：" + indent.getIndentNumber());
        userMoneyDetails.setType(1);
        userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
        userMoneyDetailsService.save(userMoneyDetails);


        //代理城市明细
        AgentCityDetails agentCityDetails = new AgentCityDetails();
        agentCityDetails.setCityId(indent.getCityId());
        agentCityDetails.setClassify(1);
        agentCityDetails.setType(1);
        agentCityDetails.setTitle("订单分成,编号：" + indent.getIndentNumber());
        stringBuilder=new StringBuilder();
        stringBuilder.append("订单金额").append(indent.getIndentMoney().setScale(2, RoundingMode.FLOOR));
        if(indent.getAgentMoney()!=null && indent.getAgentMoney().doubleValue()>0){
            stringBuilder.append("，师傅金额：").append(balance.setScale(2, RoundingMode.FLOOR));
        }
        if(indent.getUserScaleMoney()!=null && indent.getUserScaleMoney().doubleValue()>0){
            stringBuilder.append("，一级推广金额：").append(indent.getUserScaleMoney().setScale(2, RoundingMode.FLOOR));
        }
        if(indent.getUserTwoMoney()!=null && indent.getUserTwoMoney().doubleValue()>0){
            stringBuilder.append("，二级推广金额：").append(indent.getUserTwoMoney().setScale(2, RoundingMode.FLOOR));
        }
        stringBuilder.append("，平台服务费:").append(indent.getPlatformMoney().setScale(2, RoundingMode.FLOOR));
        stringBuilder.append("，到账收益:").append(indent.getAgentMoney().setScale(2, RoundingMode.FLOOR));
        agentCityDetails.setMoney(indent.getAgentMoney());
        CityInfo cityInfo = cityInfoService.getById(indent.getCityId());
        if (cityInfo != null) {
            if (cityInfo.getAgentUserId() != null) {
                AgentUserMoney agentUserMoney = agentUserMoneyService.getOne(new QueryWrapper<AgentUserMoney>().eq("sys_user_id", cityInfo.getAgentUserId()));
                agentUserMoney.setMoney(agentUserMoney.getMoney().add(indent.getAgentMoney()));
                agentUserMoneyService.updateById(agentUserMoney);
            }
            agentCityDetails.setSysUserId(cityInfo.getAgentUserId());
            agentCityDetailsService.saveAgentCityDetails(agentCityDetails);
        }


        CommonInfo userNotice = commonInfoService.findOne(307);
        CommonInfo riderNotice = commonInfoService.findOne(268);
        List<String> msgList = new ArrayList<>();

        msgList.add(0, indent.getIndentNumber());
        String address = indent.getShipAddress() + "" + indent.getDeliveryAddress();
        if (address.length() >= 20) {
            address = address.substring(0, 15) + "...";
        }
        msgList.add(1, address);
        msgList.add(2, "支付成功");
        msgList.add(3, "诚邀您为本次服务进行评价");
        if (userEntity!=null && StringUtils.isNotEmpty(userEntity.getOpenId())) {
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), userNotice.getValue(), msgList, 3);
        }
        msgList.add(3, "用户已付款,佣金已结算");
        if (StringUtils.isNotEmpty(riderEntity.getRiderOpenId())) {
            SenInfoCheckUtil.sendRiderMsg(riderEntity.getRiderOpenId(), riderNotice.getValue(), msgList, 2);
        }
        //app端用户消息推送
        if (userEntity!=null && StringUtils.isNotEmpty(userEntity.getClientid())) {

            String content = "亲爱的顾客，诚邀您为本次服务进行评价";
            userService.pushToSingle("订单状态通知", content, userEntity.getClientid());
        }
        //app端师傅消息推送
        if (StringUtils.isNotEmpty(riderEntity.getClientRiderId())) {

            String content = "订单已支付，服务费将在稍后返回到您的账户";
            userService.pushToSingleQiShou("订单状态通知", content, riderEntity.getClientRiderId());
        }
        return Result.success();
    }

    @Override
    public List<IndentVo> indentExcelOut(String indentType, String indentNumber, String indentState, String phone, String date, String dateType, String startTime, String endTime, String parentName, String parentParentName, HttpServletResponse response) {
        return baseMapper.indentExcelOut(indentType, indentNumber, indentState, phone, date, dateType, startTime, endTime, parentName, parentParentName);
    }

    @Override
    public HashMap<String, Integer> getOrderSubscript(Long userId) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        //订单状态 0待接单 1已接单 2进行中 3待支付 4已完成 5已取消
        int indentWait = baseMapper.selectCount(new QueryWrapper<Indent>().eq("user_id", userId).eq("indent_state", 0));
        int indentAccept = baseMapper.selectCount(new QueryWrapper<Indent>().eq("user_id", userId).eq("indent_state", 1));
        int indentProgress = baseMapper.selectCount(new QueryWrapper<Indent>().eq("user_id", userId).eq("indent_state", 2));
        int indentWaitPay = baseMapper.selectCount(new QueryWrapper<Indent>().eq("user_id", userId).eq("indent_state", 3));
        int indentFinish = baseMapper.selectCount(new QueryWrapper<Indent>().eq("user_id", userId).eq("indent_state", 4));
        int indentCancel = baseMapper.selectCount(new QueryWrapper<Indent>().eq("user_id", userId).eq("indent_state", 5));
        hashMap.put("indentWait", indentWait);
        hashMap.put("indentAccept", indentAccept);
        hashMap.put("indentProgress", indentProgress);
        hashMap.put("indentWaitPay", indentWaitPay);
        hashMap.put("indentFinish", indentFinish);
        hashMap.put("indentCancel", indentCancel);

        return hashMap;
    }

    @Override
    public IndentVo riderGetIndentInfo(Long userId, String indentNumber) {
        IndentVo indent = indentDao.indentMessage(indentNumber);
        RiderLocation location = locationService.getOne(new QueryWrapper<RiderLocation>().eq("user_id", userId));
        if (location != null) {
            if (indent.getIndentState() == 1 && location.getLat() != null && location.getLng() != null) {
                BigDecimal distance = getDistance(location.getLat(), location.getLng(), indent.getShipAddressLatitude(), indent.getShipAddressLongitude(), 4).getDistance();
                indent.setRiderDistance(distance);
                //获取师傅离终点的距离
            } else if (indent.getIndentState() == 2 && location.getLat() != null && location.getLng() != null) {
                BigDecimal distance = getDistance(location.getLat(), location.getLng(), indent.getDeliveryAddressLatitude(), indent.getDeliveryAddressLongitude(), 1).getDistance();
                indent.setRiderDistance(distance);
            }
        }
        if (indent.getIndentState() == 0 || indent.getIndentState() == 1 || indent.getIndentState() == 2) {

            UserEntity userEntity = userService.getById(userId);

            CityInfo cityInfo = cityInfoService.getOne(new QueryWrapper<CityInfo>().eq("city_name", indent.getShipCity()));
            //扣除平台分成后的价格
            //BigDecimal agentMoney = indent.getEstimateMoney().subtract(indent.getEstimateMoney().multiply(cityInfo.getPingRate()));

            indent.setRiderMoney(indent.getEstimateMoney().multiply(new BigDecimal(userEntity.getRate())).setScale(2, RoundingMode.FLOOR));
        }
        return indent;
    }

    @Override
    public Result userEvaluate(Long userId, Evaluate evaluate) {
        Indent indent = indentDao.indentMessage(evaluate.getIndentNumber());
        indent.setEvaluateMessage(evaluate.getEvaluateMessage());
        indent.setEvaluate(evaluate.getSatisfactionFlag());
        evaluate.setUserId(indent.getUserId());
        evaluate.setRiderUserId(indent.getRiderUserId());
        evaluate.setCreateTime(LocalDateTime.now());
        evaluateService.save(evaluate);
        return Result.upStatus(indentDao.updateById(indent));
    }

    @Override
    public int getUserIndentCount(Long userId) {

        return baseMapper.getUserIndentCount(userId);

    }

    @Override
    public BigDecimal getUserIndentMoney(Long userId) {
        return baseMapper.getUserIndentMoney(userId);
    }

    @Override
    public Result riderWaitDrive(Long userId, Long indentId) {
        Indent indent = baseMapper.selectById(indentId);
        if (indent == null) {
            return Result.error("订单不存在");
        }
        if (indent.getIndentState() != 1) {
            return Result.error("订单状态已变更,请刷新后重试");
        }
        indent.setStartWaitTime(LocalDateTime.now());

        return Result.upStatus(baseMapper.updateById(indent));


    }


    @Override
    public IndentVo userIndentMessage(String indentNumber) {
        IndentVo indent = indentDao.indentMessage(indentNumber);
        RiderLocation location = locationService.getOne(new QueryWrapper<RiderLocation>().eq("user_id", indent.getRiderUserId()));
        if (location != null) {
            if (indent.getIndentState() == 1 && location.getLat() != null && location.getLng() != null) {
                BigDecimal distance = getDistance(location.getLat(), location.getLng(), indent.getShipAddressLatitude(), indent.getShipAddressLongitude(), 4).getDistance();
                indent.setRiderDistance(distance);
                //获取师傅离终点的距离
            } else if (indent.getIndentState() == 2 && location.getLat() != null && location.getLng() != null) {
                BigDecimal distance = getDistance(location.getLat(), location.getLng(), indent.getDeliveryAddressLatitude(), indent.getDeliveryAddressLongitude(), 1).getDistance();
                indent.setRiderDistance(distance);
            }
        }
        return indent;
    }


    @Override
    public Result userCancleIndent(Long userId, String indentNumber) {
        //返回订单对象
        Indent indent = indentDao.indentMessage(indentNumber);
        if (indent != null) {
            if (indent.getIndentState() != 0 && indent.getIndentState() != 1) {
                return Result.error("当前状态不允许取消！");
            }
            if (indent.getIndentState() == 1) {
                int cancelTime = Integer.parseInt(commonInfoService.findOne(359).getValue());
                Duration between = Duration.between(LocalDateTime.now(), indent.getReceivingTime());
                if (between.getSeconds() >= (cancelTime * 60L)) {
                    return Result.error("接单时间超过" + cancelTime + "分钟,无法取消");
                }

                UserEntity userEntity = userService.getById(userId);
                int cancelSub = Integer.parseInt(commonInfoService.findOne(364).getValue());
                if (userEntity.getCreditScore() < cancelSub) {
                    cancelSub = userEntity.getCreditScore();
                }
                recordService.updateUserCreditRecord(userEntity, 2, cancelSub, "取消订单扣除信用分");
            }
            indent.setIndentState(5);
            //将优惠券修改为未使用状态
            if (indent.getCouponId() != null) {
                TbCouponUser couponUser = couponUserService.getById(indent.getCouponId());
                couponUser.setStatus(0);
                couponUserService.updateById(couponUser);
            }
            indentDao.updateById(indent);
        }
        return Result.success();
    }

    @Override
    public Result riderCancelIndent(Long userId, String indentId) {
        Indent indent = baseMapper.selectById(indentId);
        if (indent.getIndentState() == 4) {
            return Result.error("当前订单已完成,无法取消");
        }
        UserEntity userInfo = userService.getById(indent.getRiderUserId());
        if (userInfo.getCashDeposit().doubleValue() <= indent.getRiderFine().doubleValue()) {
            return Result.error("您的保证金不足，不能取消该订单！");
        }
        int cancelSub = Integer.parseInt(commonInfoService.findOne(364).getValue());
        if (userInfo.getCreditScore() < cancelSub) {
            return Result.error("信用分不足,无法取消订单");
        }
        recordService.updateUserCreditRecord(userInfo, 2, cancelSub, "取消订单扣除信用分");
        indent.setIndentState(0);
        indent.setRiderUserId(null);
        //把订单改为未结单状态
        indentDao.updateById(indent);
        //返回订单对象
        //师傅取消订单后，从师傅的保证金里暂扣罚金

        //如果不是师傅下单
        if (indent.getUserId() != null) {
            BigDecimal cashDeposit = userInfo.getCashDeposit().subtract(indent.getRiderFine());
            indentDao.updateRiderCashDeposit(cashDeposit, userInfo.getUserId());
            //将扣款明细添加到钱包明细表里
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setMoney(indent.getRiderFine());
            userMoneyDetails.setUserType(2);
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("取消订单扣除保证金：" + indent.getRiderFine());
            userMoneyDetails.setTitle("取消接单");
            userMoneyDetails.setType(2);
            userMoneyDetails.setClassify(1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
            UserEntity userEntity = userService.getById(indent.getUserId());
            CommonInfo one = commonInfoService.findOne(307);
            List<String> msgList = new ArrayList<>();
            msgList.add(0, indent.getIndentNumber());
            msgList.add(1, "待接单");
            msgList.add(2, "师傅取消接单，系统正在重新寻找师傅");
            msgList.add(3, DateUtils.format(new Date()));
            if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 3);
            }
            if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                userService.pushToSingle("更换师傅", "师傅取消接单，系统正在重新寻找师傅", userEntity.getClientid());
            }
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState(String.valueOf(4));
            messageInfo.setContent("师傅取消接单，系统正在重新寻找师傅");
            messageInfo.setTitle("师傅取消订单");
            messageInfo.setUserName(userEntity.getNickName());
            messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = new Date();
            messageInfo.setCreateAt(sdf.format(now));
            messageInfo.setIsSee("0");
            messageService.save(messageInfo);
        } else {
            indent.setIndentState(4);
            baseMapper.updateById(indent);
        }


        return Result.success();
    }

    public String generateOrder() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(new Date());
        Random random = new Random();
        int i = (int) ((Math.random() * 9 + 1) * 10000);
        return format + i;
    }

}
